package com.caj.item;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/*
    延迟队列中的元素（需实现Delay接口）
 */
public class Item<T> implements Delayed {

    //到期时间
    private long expireTime;
    //业务数据
    T data;

    public T getData(){
        return data;
    }

    public Item(long lockTime, T data){
        this.expireTime = lockTime + System.currentTimeMillis() - 1000;
        this.data = data;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long delay = unit.convert(this.expireTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        return delay;
    }

    @Override
    public int compareTo(Delayed o) {
        long result = getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
        if(result > 0){
            return 1;
        }else if (result < 0){
            return -1;
        }else {
            return 0;
        }
    }
}
